<?php
namespace app\common\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use think\Log;
use app\common\request\Curl;
use app\common\request\ClientLai;
use app\common\model\CarsInfo;
use think\Exception;
use app\common\model\Cars;

class Upgrade extends Command
{


	protected function configure()
    {
        $this->setName('upgrade')->setDescription('切IOT');
    }

    protected function execute(Input $input, Output $output)
    {
        $sTime = microtime(true);
        $info = self::getCarsInfo();
        if($info){
            $car_unique_id = array_column($info,'car_unique_id');
            $cars = self::getCars($car_unique_id);
            if($cars){
                foreach ($cars as $key => $value) {
                    Log::record('切IOT车辆:'.$value['car_unique_id'],'log');
                    if($value['band_status'] == 1){
                        Log::record('未解绑车辆:'.$value['car_unique_id'],'log');

                        if(self::unBandCars($value['supplier_no'],$value['car_unique_id'])){
                            $arr = self::queryDetail($value['equipment_id']);
                            if($arr['data'][0]['success'] == true){
                                $productKey = $arr['data'][0]['data']['productKey'];
                                $deviceSecret = $arr['data'][0]['data']['deviceSecret'];
                                $car_unique_id = $value['car_unique_id'];
                                self::current($productKey,$deviceSecret,$car_unique_id);

                            }else{
                                Log::record('未注册设备:'.$value['equipment_id'],'log');

                                if(self::register($value['equipment_id'])){
                                    
                                    $arr = self::queryDetail($value['equipment_id']);
                                    if($arr['data'][0]['success'] == true){
                                        $productKey = $arr['data'][0]['data']['productKey'];
                                        $deviceSecret = $arr['data'][0]['data']['deviceSecret'];
                                        $car_unique_id = $value['car_unique_id'];
                                        self::current($productKey,$deviceSecret,$car_unique_id);
                                            
                                    }
                                    
                                }
                            }  
                        }

                    }else{
                        $arr = self::queryDetail($value['equipment_id']);

                        if($arr['data'][0]['success'] == true){

                            $productKey = $arr['data'][0]['data']['productKey'];
                            $deviceSecret = $arr['data'][0]['data']['deviceSecret'];
                            $car_unique_id = $value['car_unique_id'];
                            self::current($productKey,$deviceSecret,$car_unique_id);
                               

                        }else{
                            Log::record('未注册设备:'.$value['equipment_id'],'log');

                            if(self::register($value['equipment_id'])){
                                $arr = self::queryDetail($value['equipment_id']);
                                if($arr['data'][0]['success'] == true){
                                    $productKey = $arr['data'][0]['data']['productKey'];
                                    $deviceSecret = $arr['data'][0]['data']['deviceSecret'];
                                    $car_unique_id = $value['car_unique_id'];
                                    self::current($productKey,$deviceSecret,$car_unique_id);
                                      
                                }
                            }
                        }   
                    }
                }
                
            }
        }

    	$eTime = microtime(true);
        $time = $eTime - $sTime;
        $output->writeln('消耗时间'.$time.'秒');
    } 

    public static function getCarsInfo(){
        try{

            $info = Db::name('cars_info')->where(['network_status'=>1,'supplier_no'=>1376920002])->limit(20)->field('car_unique_id')->select();


        }catch(\Exception $e){
 
            Log::record('getCarsInfo:'.$e->getMessage(),'error');
        }
        
        return $info;
    }

    public static function getCars($car_unique_id){
        try{

            $cars = Db::name('cars')->where(['agency_id'=>8])->where('car_unique_id','in',$car_unique_id)->field('car_unique_id,equipment_id,band_status,supplier_no,car_sn')->select();

        }catch(\Exception $e){

            Log::record('getCars:'.$e->getMessage(),'error');
        }

        return $cars;
            
    }

    public static function unBandCars($supplier_no,$car_unique_id){
        $config = config('blt_lai');
        $obj = new ClientLai($config['user_name'],$config['password']);

        $data['supplier_no'] = $supplier_no;
        $data['car_unique_id'] = $car_unique_id;
        
        $res = $obj->request_post(rtrim($config['url'],'/').'/unbind_car',$data);

        $arr = json_decode($res,true);

        if($arr['result']==0){          
            try{
                
                Db::name('cars')->where(['car_unique_id'=>$car_unique_id])->update(['band_status'=>0]);
                
            }catch(\Exception $e){
                Log::record('更新车辆绑定状态(解绑):'.$e->getMessage(),'error');
            }

            return true;

        }else{
            Log::record('未解绑成功车辆:'.$car_unique_id,'log');
        }

    }

    public static function queryDetail($equipment_id){
        $config = config('local_iot');
        $obj = new ClientLai($config['user_name'],$config['password']);

        $data['device_name'] = $equipment_id;
        $res = $obj->request_post(rtrim($config['url'],'/').'/device/queryDeviceDetail',$data);
        if($res){
            $arr = json_decode($res,true);
            
        }else{
            $arr = null;
        }
        
        return $arr;
    }

    public static function register($equipment_id){
        $config = config('local_iot');
        $obj = new ClientLai($config['user_name'],$config['password']);
        $data['device_name'] = $equipment_id;
        $res = $obj->request_post(rtrim($config['url'],'/').'/device/registDevice',$data);
        $arr = json_decode($res,true);
        if($arr['result'] == 0){
            if($arr['data'][0]['success'] == true){
                Db::name('terminal')->where(['equipment_id'=>$equipment_id])->update(['status'=>1]);
            }

            return true;

        }else{
            Log::record('设备未注册成功'.$equipment_id,'log');
        }

    }

    public static function current($productKey,$deviceSecret,$car_unique_id){
        $data['productKey'] = $productKey;
        $data['deviceSecret'] = $deviceSecret;
        $data['car_unique_id'] = $car_unique_id;
        $config = config('gz_blt'); 
        $obj = new ClientLai($config['user_name'],$config['password']);
        $res = $obj->request_post(rtrim($config['url'],'/').'/api/vehicle/updateIot',http_build_query($data));
        $arr = json_decode($res,true);
        if($arr['result'] == 0){

            try{

                Db::name('cars_info')->where(['car_unique_id' => $car_unique_id])->update(['supplier_no' => 1376920003]);

            }catch(\Exception $e){
                Log::record('更新CarsInfo厂商:'.$e->getMessage(),'error');
            }

            try{

                Db::name('cars')->where(['car_unique_id' => $car_unique_id])->update(['supplier_no' => 1376920003]);

            }catch(\Exception $e){
                Log::record('更新Cars厂商:'.$e->getMessage(),'error');
            }
            Log::record('切换IOT成功车辆:'.$car_unique_id,'log');

            return true;

        }else{
            Log::record('切换IOT失败车辆:'.$car_unique_id,'log');
        }
       

    }    

    public static function bandCars($supplier_no,$car_unique_id,$equipment_id,$car_sn){
        $config = config('blt_lai');
        $obj = new ClientLai($config['user_name'],$config['password']);
        $data['supplier_no'] = $supplier_no;
        $data['car_unique_id'] = $car_unique_id;
        $data['equipment_id'] = $equipment_id;
        $data['bluetooth_id'] = ltrim($equipment_id,0);
        $data['license_plate'] = $car_sn;

        $res = $obj->request_post(rtrim($config['url'],'/').'/bind_car',$data);

        $arr = json_decode($res,true);
        if($arr['result']==0){          
            try{
                Db::name('cars')->where(['car_unique_id'=>$car_unique_id])->update(['band_status'=>1]);
                
            }catch(\Exception $e){
               Log::record('更新车辆绑定状态(绑定):'.$e->getMessage(),'error');
            }

        }else{
            Log::record('未绑定成功车辆:'.$car_unique_id,'log');
        }
    }
}